import wx

from .task_dialog import TaskDialog
from logic.config import Task,TaskMgr
import wx.propgrid as wxpg
from datetime import datetime
from gui.gui_utils import _pydate2wxdate,_wxdate2pydate
import numpy as np

class TaskDialogLogic():
    def __init__(self):
        self.win = TaskDialog(None)
        self.win.m_btn_cancel.Bind(wx.EVT_BUTTON,self.on_cancel)
        self.win.m_btn_OK.Bind(wx.EVT_BUTTON, self.on_ok)

    def on_cancel(self, event):
        self.win.Close(True)

    def on_ok(self, event):
        t = Task()
        dict = t.__class__.__dict__
        for k in dict.keys():
            if '__' not in k:
                pg_item_name = 'm_pg_{}'.format(k)
                v = self.__getattribute__(pg_item_name).GetValue()
                if type(v) is str and 'list_' in k:
                    v = v.split('\\n')

                if 'date_' in k:
                    v = _wxdate2pydate(v).strftime('%Y%m%d')
                t.__setattr__(k, v)

        print(t)
        TaskMgr().add_or_update_task(t)
        self.win.Close(True)


    def __show_task(self, task: Task):
        pg = self.win.m_pg_task

        k_to_showname ={
            'name':'策略名称',
            'date_start':'起始日期',
            'date_end':'结束日期',
            'list_codes':'投资标的池',
            'enum_weight':'权重',
            'enum_freq':'调仓频率',
            'enum_task_type':'策略类型',
            'weight_fix':'固定权重',
            'list_features':'特征列表',
            'list_buy_rules':'买入规则',
            'buy_rules_min_count':'买入规则至少满足',
            'list_sell_rules':'卖出规则',
            'sell_rules_min_count': '卖出规则至少满足',
            'orderby':'排序特征',
            'enum_orderby_dir':'排序方向'
        }

        enum_names = {'enum_task_type': ['全选', '传统量化规则选股', '机器模型选股'],
                      'enum_freq':['每天','每周','每月','每季','每年','仅运行一次'],
                      'enum_weight':['等权','固定权重'],
                      'enum_orderby_dir':['从大到小','从小到大']
                      }

        def get_show_name(name):
            if name in k_to_showname.keys():
                return k_to_showname[name]
            return name

        attrs = task.__dict__
        if len(attrs) == 0:
            attrs = task.__class__.__dict__

        cats = {
            'list_codes':'2-投资标的池',
            'orderby':'排序规则',
            'list_buy_rules': '交易信号',
            'enum_weight': '权重配置',
            'list_features': '特征标注',
        }


        pg.Append(wxpg.PropertyCategory("1 - 回测任务基础配置"))
        for k,v in attrs.items():
            if k in cats.keys():
                pg.Append(wxpg.PropertyCategory(cats[k]))

            if '__' not in k:
                if 'date_' in k:
                    dt = datetime.strptime(v, '%Y%m%d')
                    pg_item = wxpg.DateProperty(get_show_name(k),value=_pydate2wxdate(dt))
                elif 'enum' in k:
                    #dict = v.__class__.__dict__['_member_map_']
                    #print(dict.keys(),dict.values())
                    pg_item = wxpg.EnumProperty(get_show_name(k), "{}_".format(k),
                                      enum_names[k],
                                      [n+1 for n in range(len(enum_names[k]))],
                                      v)
                elif type(v) is int:
                    pg_item = wxpg.IntProperty(get_show_name(k), value=int(v))
                elif type(v) is list:#'list_' in k:
                    value = '\\n'.join(v)
                    pg_item = wxpg.LongStringProperty(get_show_name(k),k,value=value)
                else:
                    pg_item = wxpg.LongStringProperty(get_show_name(k),k,value=str(v))
                self.__dict__['m_pg_{}'.format(k)] = pg_item
                pg.Append(pg_item)

    #task = None表示要新建
    def show(self, task: Task):
        if task is None:
            task = Task()
        self.__show_task(task)
        self.win.Show()

